package com.train.webadmin.app.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.train.webadmin.app.service.*;
import com.train.webadmin.app.dao.*;
import com.train.webadmin.app.model.*;
import com.train.common.core.base.dao.BaseDaoMapper;
import com.train.common.core.object.Tuple2;
import com.train.common.core.object.TokenData;
import com.train.common.core.object.MyRelationParam;
import com.train.common.core.object.CallResult;
import com.train.common.core.base.service.BaseService;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 试卷题目关系表数据操作服务类。
 *
 * @author xulei
 * @date 2025-03-07
 */
@Slf4j
@Service("tPaperQuestService")
public class TPaperQuestServiceImpl extends BaseService<TPaperQuest, Long> implements TPaperQuestService {

    @Autowired
    private TPaperQuestMapper tPaperQuestMapper;
    @Autowired
    private TQuestionInfoService tQuestionInfoService;
    @Autowired
    private TPaperInfoService tPaperInfoService;

    /**
     * 返回当前Service的主表Mapper对象。
     *
     * @return 主表Mapper对象。
     */
    @Override
    protected BaseDaoMapper<TPaperQuest> mapper() {
        return tPaperQuestMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public TPaperQuest saveNew(TPaperQuest tPaperQuest) {
        tPaperQuestMapper.insert(this.buildDefaultValue(tPaperQuest));
        return tPaperQuest;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewBatch(List<TPaperQuest> tPaperQuestList) {
        if (CollUtil.isNotEmpty(tPaperQuestList)) {
            tPaperQuestList.forEach(this::buildDefaultValue);
            tPaperQuestMapper.insertList(tPaperQuestList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewOrUpdateBatch(List<TPaperQuest> tPaperQuestList, List<String> duplicateVerifyColumns, int batchSize) {
        if (CollUtil.isEmpty(tPaperQuestList)) {
            return;
        }
        if (batchSize <= 0) {
            batchSize = CollUtil.isNotEmpty(duplicateVerifyColumns) ? 100 : 10000;
        }
        int start = 0;
        do {
            int end = Math.min(tPaperQuestList.size(), start + batchSize);
            List<TPaperQuest> subList = tPaperQuestList.subList(start, end);
            if (CollUtil.isNotEmpty(duplicateVerifyColumns)) {
                Tuple2<List<TPaperQuest>, List<TPaperQuest>> t = this.deduceInsertOrUpdateList(subList, duplicateVerifyColumns);
                if (CollUtil.isNotEmpty(t.getFirst())) {
                    t.getFirst().forEach(this::buildDefaultValue);
                    tPaperQuestMapper.insertList(t.getFirst());
                }
                t.getSecond().forEach(data -> tPaperQuestMapper.updateById(data));
            } else {
                tPaperQuestList.forEach(this::buildDefaultValue);
                tPaperQuestMapper.insertList(subList);
            }
            if (end == tPaperQuestList.size()) {
                break;
            }
            start += batchSize;
        } while (true);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(TPaperQuest tPaperQuest, TPaperQuest originalTPaperQuest) {
        tPaperQuest.setCreateUserId(originalTPaperQuest.getCreateUserId());
        tPaperQuest.setUpdateUserId(TokenData.takeFromRequest().getUserId());
        tPaperQuest.setCreateTime(originalTPaperQuest.getCreateTime());
        tPaperQuest.setUpdateTime(new Date());
        // 这里重点提示，在执行主表数据更新之前，如果有哪些字段不支持修改操作，请用原有数据对象字段替换当前数据字段。
        UpdateWrapper<TPaperQuest> uw = this.createUpdateQueryForNullValue(tPaperQuest, tPaperQuest.getId());
        return tPaperQuestMapper.update(tPaperQuest, uw) == 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(Long id) {
        return tPaperQuestMapper.deleteById(id) == 1;
    }

    @Override
    public List<TPaperQuest> getTPaperQuestList(TPaperQuest filter, String orderBy) {
        return tPaperQuestMapper.getTPaperQuestList(filter, orderBy);
    }

    @Override
    public List<TPaperQuest> getTPaperQuestListWithRelation(TPaperQuest filter, String orderBy) {
        List<TPaperQuest> resultList = tPaperQuestMapper.getTPaperQuestList(filter, orderBy);
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }

    @Override
    public CallResult verifyImportList(List<TPaperQuest> dataList, Set<String> ignoreFieldSet) {
        CallResult callResult;
        if (!CollUtil.contains(ignoreFieldSet, "questionId")) {
            callResult = verifyImportForDatasourceDict(dataList, "questionIdDictMap", TPaperQuest::getQuestionId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "paperId")) {
            callResult = verifyImportForDatasourceDict(dataList, "paperIdDictMap", TPaperQuest::getPaperId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        return CallResult.ok();
    }

    @Override
    public CallResult verifyRelatedData(TPaperQuest tPaperQuest, TPaperQuest originalTPaperQuest) {
        String errorMessageFormat = "数据验证失败，关联的%s并不存在，请刷新后重试！";
        //这里是基于字典的验证。
        if (this.needToVerify(tPaperQuest, originalTPaperQuest, TPaperQuest::getQuestionId)
                && !tQuestionInfoService.existId(tPaperQuest.getQuestionId())) {
            return CallResult.error(String.format(errorMessageFormat, "题目id"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(tPaperQuest, originalTPaperQuest, TPaperQuest::getPaperId)
                && !tPaperInfoService.existId(tPaperQuest.getPaperId())) {
            return CallResult.error(String.format(errorMessageFormat, "试卷id"));
        }
        return CallResult.ok();
    }

    private TPaperQuest buildDefaultValue(TPaperQuest tPaperQuest) {
        TokenData tokenData = TokenData.takeFromRequest();
        tPaperQuest.setCreateUserId(tokenData.getUserId());
        tPaperQuest.setUpdateUserId(tokenData.getUserId());
        Date now = new Date();
        tPaperQuest.setCreateTime(now);
        tPaperQuest.setUpdateTime(now);
        return tPaperQuest;
    }
}
